MML_CSV_带源码 -带UI.py

MML_CSV_带源码 -带UI.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-


from doctest import OutputChecker
import os
import re
import pandas as pd
import zipfile
import os
import rarfile
import shutil
from datetime import datetime
import pandas as pd
import tarfile
import threading
from tkinter import*
from tkinter.filedialog import askdirectory #导入askdirectory函数


#现在时间   
now_time = datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
#全局变量
Config_list='''

#通用
CNACLD
PFXPRO
SCCPGT
DNC
CLRDSG
CLDPREANA
INNUMPREPRO
ROAMRESTGRP
SMMOPRO
ROAMUSRT
IMSIGT
#路由类
N7DSP
OFC
RT
RTANA
SRT
SCCPADDRPL

#号码分析类
CNACLR
CLICRTANA
CALLPRICHK

#智能网
SCPINFO
SCPPARA
TDPAC
SCPCFG

#DNS
DZONE

#PSBC
USERINFO

#ISBG
SNRTANA
IDMNA
ISCAP
SENUMNP
IDMRTANA
INRTANA
SRTADDR
SRTSSC
SCLRNA
SRTANA

#TAS
PFXTOL
CNACLDMT
CLDPREUNI
MBLPFX
NUMSEGSRCMAP
FMCBLKNUM

#HSS
CALLEDNA
NPPREFIXRN

#IBCF
INRTANA

#HWDRA
RTIMSI
RTMSISDN
RTIMPU
RTIMPI

'''

#全局列表
quanj_list=[]


 #文件解压流程
    #1.解压文件
    #2.重命名文件,并转移到指定目录
def File_jieya(dir_path):
    #解压目录
    MML_Context = os.path.join(dir_path, "MML转录表格")
    print("解压目录:"+MML_Context)
    #强制删除文件夹
    if(os.path.exists(MML_Context)):
        shutil.rmtree(MML_Context)
    #创建文件夹
    # if(not os.path.exists(MML_Context)):
    #     os.mkdir(MML_Context)
    
    
    for file in os.listdir(dir_path):
        file = os.path.join(dir_path, file)
        if  file.endswith(".tar.gz"):
            #print(file.split("\\")[1].split(".tar.gz")[0]+".txt")
            #print(MML_Context)
            tf = tarfile.open(file)
            #print(tf.getnames())
            tf.extractall(MML_Context)
            file_name = MML_Context+"/"+tf.getnames()[0]            
            os.rename(file_name,file_name.replace(tf.getnames()[0],file.split("\\")[1].split(".tar.gz")[0]+".txt"))
            #print(file_name)

    os.startfile(MML_Context)
    return MML_Context
    

#3.解析文件
#解析函数
def Parse_MML_sub(file,sheet_list,flag_yuanma):
    #读取TXT文件
    try:
        TXT_Content = open(file, 'r',encoding='UTF-8').read()
    except:
        TXT_Content = open(file, 'r',encoding='GBK').read()
    finally:
        #此处可控制读取行数
        #raw = TXT_Content.split("\n")[0:1000]
        raw = TXT_Content.split("\n")
        Print_t("\n"+"文件名:"+file+"\n"+"文件行数:"+str(len(raw))+"\n")
        
        index = 0

        #列表字典        
        dict_temp = {}
        #列表行集合
        dict_temp_lsit = []
        
        #读表记录
        sheet_name_list = ["记录"]
        #逐行读取
        for line in raw:
            #print(line)
            if(re.findall("(?<=ADD).*(?=:)", line)):
                sheet_name = re.search("(?<=ADD).*(?=:)", line).group().strip()
                #检测到表切换时清空列表
                if(sheet_name_list[-1] != sheet_name):
                    sheet_name_list.append(sheet_name)
                    dict_temp_lsit = []
            #获取文件名
                #获取关键行号
                #print(index)
                #行解析字典
                dict_temp_sub = {}
                #核对表名
                if(sheet_name in sheet_list):
                #if(True):
                    #创建表格收集
                    #sheet_Context
                    
                    #获取表名
                    #print("表名:"+sheet_name)
                    temp_l = line.split(":")[1].split(",")
                    for i in temp_l:
                        #按字段分列
                        dict_temp_sub[i.split("=")[0]] = i.split("=")[1].strip('"')

                    if(flag_yuanma == 1):
                        #添加源码行到最后
                        dict_temp_sub["源码MML"] = line


                    dict_temp_lsit.append(dict_temp_sub)  
                    
                    dict_temp[sheet_name] = dict_temp_lsit
                    #print(len(dict_temp_lsit))                                                        
            index = index + 1


        #写入excel文件
        output_file = os.path.splitext(file)[0]+'output.xlsx'
        writer = pd.ExcelWriter(output_file)
        for key,value in dict_temp.items():
            #print(value)                   
            
            #写入excel文件
            pd.DataFrame(value).to_excel(writer,key,index=False)                    
            #print(su)
        writer.save()
        #os.startfile(output_file)
        Print_t("文件解析完成:"+output_file)

        #output_text.insert("end", "\n文件解析完成:"+output_file)
        

#test
def test(file):
    print(file)
    #输出现在时间
    print(now_time)
    
    return file


#多线程执行函数
def Parse_MML(dir_path,sheet_list,flag_yuanma):
    #读取配置
    print(sheet_list)

   #输出文件夹
    #MML_OUTPUT = os.path.join(os.path.dirname(dir_path_o), "MML转录表格")

    #文件解析流程
    #获取文件夹下所有文件
    #
    #print(os.listdir(dir_path))

    Print_t("开始时间:"+now_time)
    for file in os.listdir(dir_path):
        file = os.path.join(dir_path, file)
        if  file.endswith(".txt"):
            #print(file)
            #test(file)
            #多线程执行   
            #print(os.path.splitext(file))              
            threading.Thread(target=Parse_MML_sub, args=(file,sheet_list,flag_yuanma,)).start()
            #Parse_MML_sub(file)

#配置读取
def Config_Read(Config_list):
    sheet_list =[]
    for line in Config_list.split("\n"):
        if(line.startswith("#")):
            continue
        elif("" == line):
            continue            
        sheet_list.append(line)
        #print(line)
    #print(sheet_list)
    return sheet_list    
       
#本地保存配置
#本地配置文件读取函数
def read_config(filename):
    sheet_list =[]
    with open(filename) as r:        
        for line in r.readlines():
            line = line.split("\n")[0]
            if(line.startswith("#")):
                continue
            elif("" == line):
                continue            
            sheet_list.append(line)
            #print(line)
    
    return sheet_list    
        
    return config



#本地配置文件写入函数
def write_config(Config_list,filename):
    #字典转json
    with open(filename,'w') as f:
     # 设置不转换成ascii  json字符串首缩进
        f.write(Config_list)
    return Config_list



############################################################################
if __name__ == '__main__':
    tip = '''
 配置文件MML转表格工具
 1、本程序存在预配置,第一次自动生成Config.txt后可进行配置修改
 2、本程序可读取同目录下的配置(跳过#,空行)
 3、本程序默认使用TK组件获取目标文件夹路径(目标文件为所有.tar.gz文件)
 4、本程序基于正则实现文件解析,支持MML.tar.gz文件批量解压、改文件名、解析表格,分表等功能
 5、生成Config.txt后可进行配置修改

 请确认已了解本程序功能且同意使用,谢谢!(按确认键(回车键)启动)
\n'''


####简单命令行版本
#     input('''
# 配置文件MML转表格工具
# 1、本程序存在预配置,第一次自动生成Config.txt后可进行配置修改
# 2、本程序可读取同目录下的配置(跳过#,空行)
# 3、本程序默认使用TK组件获取目标文件夹路径
# 4、本程序基于正则实现文件解析,支持MML.tar.gz文件批量解压、改文件名、解析表格,分表等功能
# 5、生成Config.txt后可进行配置修改

# 请确认已了解本程序功能且同意使用,谢谢!(按任意键继续)
#     ''')

#     #程序开始
#     try:
#         sheet_list = Config_Read(Config_list)
#         #sheet_list = ["SCCPLDSH","SCCPGTG","N7RT"]#测试

#         #写入文件,并读取
#         if(os.path.exists("./Config.txt") == False):
#             print("欢迎使用本工具,当前目录无配置文件,自动应用预配置,并生成预配置文件")
#             write_config(Config_list,'./Config.txt')
        
        
#         sheet_list = read_config('./Config.txt')
#         print("./Config.txt 配置读取成功")
#         #print(Config)

#         #TK路径选择
#         root=Tk()
#         path=StringVar()
#         path_=askdirectory()
#         path.set(path_)

#         dir_path =path_  
#         #dir_path = "."
#         print("当前路径:"+dir_path)  
    
    
#     #文件解析函数
#         Parse_MML(File_jieya(dir_path),sheet_list)
#     except TypeError:
#         print(TypeError)
#         write_config(TypeError,'./ERROR.txt')
    
#     #os.system("pause")

####UI版本
    import tkinter as tk
    from ttkbootstrap import Style
    from tkinter import ttk

    def show_config():
        os.startfile("Config.txt") 
        output_text.delete("1.0", "end")

        output_text.insert("1.0", tip)


    def confirm():
        output_text.delete("1.0", "end")

        try:
            sheet_list = Config_Read(Config_list)
            #sheet_list = ["SCCPLDSH","SCCPGTG","N7RT"]#测试

            #写入文件,并读取
            if(os.path.exists("./Config.txt") == False):
                Print_t("欢迎使用本工具,当前目录无配置文件,自动应用预配置,并生成预配置文件")
                write_config(Config_list,'./Config.txt')
            
            
            sheet_list = read_config('Config.txt')
            Print_t("Config.txt 配置读取成功")
            #print(Config)

            #TK路径选择
            root=Tk()
            path=StringVar()
            path_=askdirectory()
            path.set(path_)

            dir_path =path_  
            #dir_path = "."
            print("当前路径:"+dir_path)  
        
        
        #文件解析函数
            Parse_MML(File_jieya(dir_path),sheet_list,toggle_source_code())
        except TypeError:
            print(TypeError)
            write_config(TypeError,'./ERROR.txt')

    def toggle_source_code():
        status = var_show_source_code.get()
        if status == 1:
            print('源码已显示')
            output_text.insert("end",'源码已显示\n')
        else:
            print('源码已隐藏')
            output_text.insert("end", '源码已隐藏\n')
        return status
    
        #重写显示函数
    def Print_t(Content,File_duixiang=None):
        #print(Content)
        print(Content)
        output_text.insert(INSERT, Content)
        output_text.insert(INSERT, "\n")
        # File_duixiang.write(Content)
        # File_duixiang.write("\n")


    root = tk.Tk()
    root.title("配置文件MML转表格工具")

    # 设置窗口大小及居中显示
    width, height = 640, 400
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x = int(screen_width / 2 - width / 2)
    y = int(screen_height / 2 - height / 2)
    root.geometry("{}x{}+{}+{}".format(width, height, x, y))

    style = Style(theme='yeti')

    # 创建 ttk.Style 对象,用于设置按钮样式
    ttk_style = ttk.Style()
    ttk_style.theme_use('yeti')  # 使用默认主题

    # 设置 primary.TButton 样式(绿色)
    ttk_style.configure('primary.TButton', font=("微软雅黑", 18), padding=10)


    frame1 = tk.Frame(root)
    frame1.pack(side="top", fill="x", padx=10, pady=10)

    btn_show_config = ttk.Button(frame1, text="查看配置", command=show_config, style='primary.TButton',
                                cursor="hand2")
    btn_show_config.pack(side="left", padx=10)

    btn_confirm = ttk.Button(frame1, text="确认", command=confirm, style='primary.TButton',
                            cursor="hand2")
    btn_confirm.pack(side="left", padx=10)
    # 绑定回车键
    root.bind('<Return>', lambda event: confirm())

    var_show_source_code = tk.BooleanVar()
    chk_show_source_code = tk.Checkbutton(frame1, text="确认显示源码", variable=var_show_source_code,command=toggle_source_code, font=("微软雅黑", 18))
    chk_show_source_code.pack(side="left", padx=10)


    frame2 = tk.Frame(root)
    frame2.pack(side="bottom", fill="both", expand=True, padx=10, pady=10)

    output_text = tk.Text(frame2, height=3, width=80, font=("微软雅黑", 12))
    output_text.pack(side="left", fill="both", expand=True, padx=5, pady=5)

    scrollbar = tk.Scrollbar(frame2, command=output_text.yview)
    scrollbar.pack(side="right", fill="y")


    output_text.config(yscrollcommand=scrollbar.set)

    # output_text.insert("1.0", "\n配置文件MML转表格工具\n")
    # output_text.insert("end", "1、本程序存在预配置,第一次自动生成Config.txt后可进行配置修改\n")
    # output_text.insert("end", "2、本程序可读取同目录下的配置(跳过#,空行)\n")
    # output_text.insert("end", "3、本程序默认使用TK组件获取目标文件夹路径\n")
    # output_text.insert("end", "4、本程序基于正则实现文件解析,支持MML.tar.gz文件批量解压、改文件名、解析表格,分表等功能\n")
    # output_text.insert("end", "5、生成Config.txt后可进行配置修改\n\n")
    # output_text.insert("end", "请确认已了解本程序功能且同意使用,谢谢!(按任意键继续)\n")
#    output_text.config(state="disabled")
    output_text.insert("1.0", tip)

    root.mainloop()